package com.longy.gulimall.product.service.impl;

import com.longy.common.utils.PageUtils;
import com.longy.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.longy.gulimall.product.entity.AttrEntity;
import com.longy.gulimall.product.service.AttrAttrgroupRelationService;
import com.longy.gulimall.product.service.AttrService;
import com.longy.gulimall.product.vo.AttrGroupWithAttrsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longy.common.utils.Query;

import com.longy.gulimall.product.dao.AttrGroupDao;
import com.longy.gulimall.product.entity.AttrGroupEntity;
import com.longy.gulimall.product.service.AttrGroupService;
import org.springframework.util.StringUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Integer catId) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catId);
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_group_id",key).or().like("attr_group_name",key);
            });
        }

        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    /**
     * 根据三级分类id查询出所有分组以及关联属性
     *
     * @param catelogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrsVo> getAttrWithattrByCatelogId(Long catelogId) {
        //查询所有分组
        List<AttrGroupEntity> attrGroups = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //查询所有的关联属性
        List<AttrGroupWithAttrsVo> collect = attrGroups.stream().map(item -> {
            AttrGroupWithAttrsVo vos = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(item, vos);
            List<AttrEntity> Attrs = attrService.getRelationAttr(vos.getAttrGroupId());
            vos.setAttrs(Attrs);
            return vos;
        }).collect(Collectors.toList());
        return collect;
    }

}